package main

import (
	"blog_service/model"
	"blog_service/setting"
	"blog_service/src/admin"
	"fmt"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/robfig/cron"
	"time"
)
import "blog_service/src/lead"
import _ "blog_service/model"

func userInit() {
	users := make([]model.AdminUser, 10)
	var username, pwd, pwds string
	model.Db.Find(&users)
	if len(users) == 0 {
		fmt.Println("你现在没用管理员需要创建一个管理员：")
		fmt.Println("[username: ]")
		fmt.Scanf("%s", &username)

		for true {
			fmt.Println("请输入密码")
			fmt.Scanf("%s", &pwd)
			fmt.Println("请再次输入密码")
			fmt.Scanf("%s", &pwds)
			if pwd == pwds {
				fmt.Println(fmt.Sprintf("用户名：%s\n密码：%s\n注册成功", username, pwd))
				break
			} else {
				fmt.Println("密码错误请重新输入")
			}
		}

		pwd = admin.SHA256(pwd)
		user := model.AdminUser{Username: username, Password: pwd}
		model.Db.Create(&user)

	}

}

func main() {
	userInit()

	router := gin.Default()
	router.Use(cors.New(cors.Config{
		AllowOriginFunc:  func(origin string) bool { return true },
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "PATCH"},
		AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}))

	//admin := router.Group("/admin")
	leads := router.Group("/default")

	{
		leads.GET("/index", lead.Index)
		leads.GET("/list", lead.GetArticleList)
		leads.GET("/article", lead.GetArticleById)
		leads.GET("/getType", lead.GetTypeInfo)
		leads.GET("/getListById", lead.GetListById) //获取一个类型的全部
	}

	admins := router.Group("/admin")

	{
		admins.POST("/login", admin.Login)
		admins.GET("/getType", lead.GetTypeInfo, admin.Logger())
		admins.POST("/addArticle", admin.AddArticle, admin.Logger())
		admins.POST("/updateArticle", admin.UpdateArticle, admin.Logger())
		admins.GET("/articleList", lead.GetArticleList)
		admins.POST("/deleteArticle", admin.DeleteArticle, admin.Logger())
		admins.GET("/getArticleById", lead.GetArticleById)
	}

	go func() { //定时跟新点击数
		crontab := cron.New()
		crontab.AddFunc("0 30 23 * * *", func() {
			articles := make([]model.Article, 1)
			model.Db.Find(&articles)
			for _, item := range articles {
				comment := lead.ReadComment(fmt.Sprintf("%d", item.ID), false)

				if comment > item.ViewCount {
					item.ViewCount = comment
					model.Db.Save(&item)
				}

			}

		})

		crontab.Start()

	}()

	router.Run(setting.Addr)
	model.Db.Close()
}
